package cn.wostore.wxhelper.ui.forward;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.OnClick;
import cn.wostore.wxhelper.R;
import cn.wostore.wxhelper.adapter.ChildAdapter;
import cn.wostore.wxhelper.adapter.GroupAdapter;
import cn.wostore.wxhelper.adapter.MasterAdapter;
import cn.wostore.wxhelper.adapter.OnItemClickListener;
import cn.wostore.wxhelper.base.BaseActivity;
import cn.wostore.wxhelper.bean.*;
import cn.wostore.wxhelper.utils.WXInfoHelper;
import cn.wostore.wxhelper.utils.DaoHandler;
import cn.wostore.wxhelper.widget.CustomToolBar;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wuch
 * @date 2018/12/28 0028
 */
public class RuleSetActivity extends BaseActivity {
    @BindView(R.id.tool_bar)
    CustomToolBar mCustomToolBar;
    @BindView(R.id.btn_select_main_group)
    TextView mainGroupButton;
    @BindView(R.id.btn_select_master)
    TextView masterButton;
    @BindView(R.id.btn_select_child_group)
    TextView childGroupButton;
    @BindView(R.id.tv_main_group)
    TextView mainGroupTextView;
    @BindView(R.id.tv_master)
    TextView masterTextView;
    @BindView(R.id.tv_child_group)
    TextView childGroupTextView;
    @BindView(R.id.btn_save)
    TextView saveButton;

    private List<Group> groupList, childGroupList = new ArrayList<>(), selectGroups = new ArrayList<>();
    private Group mainGroup = null;
    private User master;
    private AlertDialog mainGroupDialog, masterDialog, childGroupDialog;
    private ForwardRule forwardRule;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_rule;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView(Bundle savedInstanceState) {
        initToolBar();
        initEvent();
    }

    private void initToolBar(){
        mCustomToolBar.setShowBack(true);
        mCustomToolBar.setShowTitle(true);
        mCustomToolBar.setTitle("新增转发规则");
        mCustomToolBar.setOnCustomToolBarListener(new CustomToolBar.OnCustomToolBarListener() {
            @Override
            public void onBackClick() {
                finishAndBack();
            }

            @Override
            public void onRightActionItemClick() {
            }
        });
    }

    private void initEvent() {
        //获取微信群组信息
        WXInfoHelper wxInfoHelper = new WXInfoHelper();
        groupList = wxInfoHelper.getGroups();
    }


    @OnClick({R.id.btn_select_main_group, R.id.btn_select_master, R.id.btn_select_child_group, R.id.btn_save})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_select_main_group:
                if (mainGroupDialog == null) {
                    initMainGroupDialog();
                }
                mainGroupDialog.show();
                break;
            case R.id.btn_select_master:
                if (mainGroup == null){
                    Toast.makeText(this, "请先选择主讲群", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mainGroupDialog == null) {
                    initMainGroupDialog();
                }
                masterDialog.show();
                break;
            case R.id.btn_select_child_group:
                if (mainGroup == null){
                    Toast.makeText(this, "请先选择主讲群", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (master == null){
                    Toast.makeText(this, "请先选择主讲人", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mainGroupDialog == null) {
                    initMainGroupDialog();
                }
                childGroupDialog.show();
                break;
            case R.id.btn_save:
                if (mainGroup == null){
                    Toast.makeText(this, "请先选择主讲群", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (master == null){
                    Toast.makeText(this, "请先选择主讲人", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (childGroupList == null){
                    Toast.makeText(this, "请先选择群发目标", Toast.LENGTH_SHORT).show();
                    return;
                }
                saveRule();
                finishAndBack();
                break;
            default:
                break;
        }
    }

    /**
     * 初始化主讲群选择对话框
     */
    private void initMainGroupDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_select, null);
        SearchView searchView = view.findViewById(R.id.sv_search);
        searchView.setIconifiedByDefault(false);
        builder.setView(view).setTitle("选择直播主讲群");
        RecyclerView recyclerView = view.findViewById(R.id.rv_list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(view.getContext());
        recyclerView.setLayoutManager(layoutManager);
        final GroupAdapter groupAdapter = new GroupAdapter(groupList);
        recyclerView.setAdapter(groupAdapter);
        groupAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                groupAdapter.setSelection(position);
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                groupAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                groupAdapter.getFilter().filter(newText);
                return false;
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mainGroup = groupAdapter.getSelectGroup();
                if (mainGroup != null) {
                    mainGroupTextView.setText(mainGroup.getChatroomName());
                    masterTextView.setText("");
                    childGroupTextView.setText("");
                    updateChildGroups(mainGroup.getChatroomId());
                    initMasterDialog();
                    initChildGroupDialog();
                } else {
                    mainGroupTextView.setText("");
                    masterTextView.setText("");
                    childGroupTextView.setText("");
                    masterDialog = null;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        mainGroupDialog = builder.create();
    }

    /**
     * 初始化主讲人选择对话框
     */
    private void initMasterDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_select, null);
        SearchView searchView = view.findViewById(R.id.sv_search);
        searchView.setIconifiedByDefault(false);
        builder.setView(view).setTitle("选择直播主讲人");
        RecyclerView recyclerView = view.findViewById(R.id.rv_list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(view.getContext());
        recyclerView.setLayoutManager(layoutManager);
        final MasterAdapter masterAdapter = new MasterAdapter(mainGroup.getMembers());
        recyclerView.setAdapter(masterAdapter);
        masterAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                masterAdapter.setSelection(position);
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                masterAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                masterAdapter.getFilter().filter(newText);
                return false;
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                master = masterAdapter.getSelectUser();
                if (master != null) {
                    masterTextView.setText(master.getUserName());
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        masterDialog = builder.create();
    }

    /**
     * 初始化直播子群选择对话框
     */
    private void initChildGroupDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_select, null);
        SearchView searchView = view.findViewById(R.id.sv_search);
        searchView.setIconifiedByDefault(false);
        builder.setView(view).setTitle("选择直播子群");
        RecyclerView recyclerView = view.findViewById(R.id.rv_list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(view.getContext());
        recyclerView.setLayoutManager(layoutManager);
        final ChildAdapter childAdapter = new ChildAdapter(childGroupList);
        recyclerView.setAdapter(childAdapter);
        childAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                childAdapter.setSelected(position);
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                childAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                childAdapter.getFilter().filter(newText);
                return false;
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                selectGroups = childAdapter.getSelectGroups();
                if (selectGroups != null) {
                    StringBuilder selectGroupsString = new StringBuilder();
                    for (int i = 0; i < selectGroups.size(); i++) {
                        if (i == 0)
                            selectGroupsString.append("1.").append(selectGroups.get(i).getChatroomName());
                        else
                            selectGroupsString.append("\n").append(i + 1).append(".").append(selectGroups.get(i).getChatroomName());
                    }
                    childGroupTextView.setText(selectGroupsString);
                } else {
                    childGroupTextView.setText("");
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        childGroupDialog = builder.create();
    }

    /**
     * 每次选择直播主讲群后，更新提供选择的子群列表，从所有群中剔除选择的主讲群
     *
     * @param chatroomId 选择的主讲群的id
     */
    private void updateChildGroups(String chatroomId) {
        int position = -1;
        childGroupList.clear();
        childGroupList.addAll(groupList);
        for (int i = 0; i < groupList.size(); i++) {
            if (groupList.get(i).getChatroomId().equals(chatroomId))
                position = i;
        }
        childGroupList.remove(position);
    }

    /**
     * 保存转发规则到数据库
     */
    private void saveRule() {
        forwardRule = new ForwardRule();
        forwardRule.setForwardRuleId(null);
        forwardRule.setForwardRuleTitle("");
        forwardRule.setForwardRuleState(true);
        forwardRule.setForwardRuleIntervalState(true);
        forwardRule.setForwardMsgText(true);
        forwardRule.setForwardMsgVoice(true);
        forwardRule.setForwardMainGroupId(mainGroup.getChatroomId());
        forwardRule.setForwardMainGroupName(mainGroup.getChatroomName());
        forwardRule.setForwardMasterId(master.getUserId());
        forwardRule.setForwardMasterName(master.getUserName());
        forwardRule.setForwardChildGroupIds(getForwardChildGroupsIds());
        forwardRule.setForwardChildGroupNames(getForwardChildGroupsNames());
        DaoHandler.getInstance().insert("ForwardRule", null, forwardRule.getForwardRuleContentValues());
    }

    /**
     * 构建转发的子群的id集合字符串
     *
     * @return 转发的子群的id集合字符串
     */
    private String getForwardChildGroupsIds() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < selectGroups.size(); i++) {
            if (i == 0)
                stringBuilder.append(selectGroups.get(i).getChatroomId());
            else
                stringBuilder.append(";").append(selectGroups.get(i).getChatroomId());
        }
        return stringBuilder.toString();
    }

    /**
     * 构建转发的子群的名字集合字符串
     *
     * @return 转发的子群的名字集合字符串
     */
    private String getForwardChildGroupsNames() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < selectGroups.size(); i++) {
            if (i == 0)
                stringBuilder.append(selectGroups.get(i).getChatroomName());
            else
                stringBuilder.append(";").append(selectGroups.get(i).getChatroomName());
        }
        return stringBuilder.toString();
    }

    private void finishAndBack(){
        setResult(99);
        finish();
    }

}
